package com.sanjiahantang.youjiaclient.module.common.presenters;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.module.city.beans.CityBean;
import com.sanjiahantang.youjiaclient.module.city.views.impl.CityActivity;
import com.sanjiahantang.youjiaclient.module.common.adapters.HomeAdapter;
import com.sanjiahantang.youjiaclient.module.common.beans.HomeBean;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.models.IHomeModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.HomeModel;
import com.sanjiahantang.youjiaclient.module.common.views.HomeView;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiaclient.module.match.beans.MatchListBean;
import com.zbar.lib.CaptureActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zy on 2017/9/1.
 */

public class HomePresenter extends BaseMvpPresenter<HomeView> {

    public static final String TAG = HomePresenter.class.getName();
    private boolean isRefreshing;
    private List<MatchListBean.Detail> moreList;
    private HomeAdapter adapter;
    private RecyclerView.OnScrollListener scrollListener;
    private IHomeModel homeModel;
    private int pageCount;
    private HomeBean.Data homePageData;
    //定位
    public AMapLocationClientOption mLocationOption;
    private AMapLocationClient mLocationClient;

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public HomePresenter() {
        homeModel = new HomeModel();
    }

    public void init(Context context) {
        initAMap(context);
        initScroller();
    }


    private void initScroller() {
        scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean isBottom = recyclerView.canScrollVertically(1);
                long current = System.currentTimeMillis();
                if (!isBottom && (System.currentTimeMillis() - current == 0)) {
                    int page = getPageCount();
                    setPageCount(page + 1);
                    mView.getMoreHomePage();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        };
    }


    /**
     * 初始化高德信息
     */
    private void initAMap(final Context context) {
        mLocationOption = null;
        mLocationClient = mView.getAMapLocationClient();
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        if (city.contains("市")) {
                            city = city.replace("市", "");
                        }

                        if (city.contains("县")) {
                            city = city.replace("县", "");
                        }

                        ConfigValue.lat = aMapLocation.getLatitude();
                        ConfigValue.lon = aMapLocation.getLongitude();
                        if (TextUtils.isEmpty(ConfigValue.city)){
                            ConfigValue.city = city;

                            if (context != null){
                                loadData(context);
                            }
                        }

                        mView.setCityText(ConfigValue.city);
                    }

                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setInterval(1000 * 60 * 30);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);


        if (Build.VERSION.SDK_INT >= 23) {
            int checkPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2);
                Log.d("TTTT", "弹出提示");
            } else {
                mLocationClient.startLocation();
            }
        } else {
            mLocationClient.startLocation();
        }
    }




    public void onLayoutRefresh(final Context context) {
        if (isRefreshing) {
            return;
        } else {
            isRefreshing = true;
            mView.setLayoutRefreshing(true);
            loadData(context);
        }
    }

    public void loadData(final Context context) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            mView.onNetError(true);
            return;
        }else{
            mView.onNetError(false);
        }

        setPageCount(1);


        if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            homeModel.findToken(context, new CallBack<StringBean>() {
                @Override
                public void onSuccess(StringBean response, Context context, Object tag) {
                    if (response != null && response.getCode() == RESPONSE_CODE_SUC) {

                    } else {
                        ConfigValue.DATA_KEY = null;
                    }

                    homeModel.getHomePageData(context, new PageCallBack());
                }

                @Override
                public void onFailure(String message) {
                    ConfigValue.DATA_KEY = null;
                    homeModel.getHomePageData(context, new PageCallBack());
                }
            });
        } else {
            ConfigValue.DATA_KEY = null;
            homeModel.getHomePageData(context, new PageCallBack());
        }

    }


    public void getMoreHomePage(Context context) {
        Map<String, String> param = new HashMap<>();
        param.put("page", String.valueOf(pageCount));
        homeModel.getMoreHomePageData(context, param, new MoreCallBack());
    }


    public RecyclerView.OnScrollListener getScrollerListener() {
        return scrollListener;
    }

    public void openScanner(Activity context, Fragment fragment) {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            return;
        }

        if (TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
            LoginActivity.logout(context);
            return;
        }

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            fragment.requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);

        } else {
            Intent itCapture = new Intent(context, CaptureActivity.class);
            context.startActivityForResult(itCapture, BaseView.INTENT_SCAN);

        }
    }

    public void selectArea(Activity activity) {
        Intent it = new Intent(activity, CityActivity.class);
        activity.startActivityForResult(it, BaseView.INTENT_CITY);
    }

    public void onRequestPermissionsResult(Context context, int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent itCapture = new Intent(context, CaptureActivity.class);
                context.startActivity(itCapture);
            } else {
                mView.showToast("权限被禁止，相关功能无法使用");
            }
        } else if (requestCode == 3) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Utils.showToast(context, "phone");
            } else {
                Utils.showToast(context, "phone deny");
            }

        } else if (requestCode == 2) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mLocationClient.startLocation();
            } else {
//                Utils.showToast(context, "city deny");
            }
        }
    }

    public void onActivityResult(Context context,int requestCode, int resultCode, Intent data) {
        if (mView == null) return;
        switch (requestCode) {
            case BaseView.INTENT_CITY:
                if (resultCode == RESULT_OK) {
                    CityBean.City city = (CityBean.City) data.getSerializableExtra(BaseView.TAG_CITY);
                    mView.setCityText(city.getRegion_name());
                    loadData(context);
                }
                break;
            case BaseView.INTENT_SCAN:
                onScanPageResult(resultCode, data);
                break;
        }
    }

    public void onScanPageResult(int resultCode, Intent data) {
        if (mView == null) return;
        if(resultCode == Activity.RESULT_OK){
            StringBean flag = (StringBean) data.getSerializableExtra(BaseView.TAG_DESIGNER_BIND);
            mView.showDialog(flag.getCode() == RESPONSE_CODE_SUC,flag.getMessage());
        }
    }

    private class PageCallBack implements CallBack<HomeBean> {

        @Override
        public void onSuccess(HomeBean response, Context context, Object tag) {
            hideProgress();
            if (response != null && mView != null) {
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    mView.setLayoutRefreshing(false);
                    isRefreshing = false;
                    homePageData = response.getData();
                    adapter = new HomeAdapter(context, homePageData, (MainActivity) context);
                    mView.initRecyclerView(adapter);

                } else {
                    Log.d(TAG, "response: " + response);
                }
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }

        mView.onNetError(false);
    }

    private class MoreCallBack implements CallBack<MatchListBean> {

        @Override
        public void onSuccess(MatchListBean response, Context context, Object tag) {
            if (mView == null) return;
            mView.setLayoutRefreshing(false);
            if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                moreList = response.getData().getList();
                if (homePageData.getMatches() != null) {
                    homePageData.getMatches().addAll(moreList);
                    adapter.notifyDataSetChanged();
                } else {
                    mView.showToast("已经到底了！");
                }

            } else if (response != null && response.getCode() == RESPONSE_CODE_FAIL) {
                Utils.showToast(context,"已经到底了！");
            } else if (response != null){
                String msg = response.getMessage().toString();
                if (TextUtils.isEmpty(msg)) {

                } else
                    Utils.showToast(context,response.getMessage().toString());
            }else {
                Utils.showToast(context,"已经到底了！");
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
}
